package us.mooresr.aircraftscheduling.server.handler;

import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;

import us.mooresr.aircraftscheduling.server.BCrypt;
import us.mooresr.aircraftscheduling.server.DAO;
import us.mooresr.aircraftscheduling.shared.action.CreateUser;
import us.mooresr.aircraftscheduling.shared.action.CreateUserAction;
import us.mooresr.aircraftscheduling.shared.action.CreateUserResult;
import us.mooresr.aircraftscheduling.shared.model.User;
import us.mooresr.aircraftscheduling.shared.model.UserDetail;

import com.google.inject.Inject;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.shared.ActionException;

public class CreateUserActionHandler implements
		ActionHandler<CreateUserAction, CreateUserResult> {

	@Inject
	public CreateUserActionHandler() {
	}

	@Override
	public CreateUserResult execute(CreateUserAction action, ExecutionContext context)
			throws ActionException {
		DAO dao = new DAO();
		
		User newUser = action.getUser();

		dao.ofy().put(newUser);
		
		UserDetail newUserDetail = action.getUserDetail();
		newUserDetail.setId(newUser.getUserId());
		// The password is in cleartext.  We need to hash it.
		String plainPassword = newUserDetail.getHashedPassword();
		
		String newHashedPassword = BCrypt.hashpw(plainPassword, BCrypt.gensalt());
		
		newUserDetail.setHashedPassword(newHashedPassword);
		
		dao.ofy().put(newUserDetail);
		
		return new CreateUserResult(newUser);
		
	}

	@Override
	public void undo(CreateUserAction action, CreateUserResult result,
			ExecutionContext context) throws ActionException {
	}

	@Override
	public Class<CreateUserAction> getActionType() {
		return CreateUserAction.class;
	}
}
